package agents;

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public abstract class TickListenerAgent extends Agent {
	protected int CurrentTickCount = 0;
	protected AID TickerAgent;
	public TickListenerAgent()
	{
	}
	
	// Put agent initializations here
	protected void setup() {
		//Add action to listen to INFORM message here
		addBehaviour(new TickListenerBehaviour());
	}
	
	protected abstract void OnTickAction();
	
	private class TickListenerBehaviour extends CyclicBehaviour 
	{

		@Override
		public void action() {
			MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
														MessageTemplate.MatchConversationId("tick"));
			ACLMessage msg = myAgent.receive(mt);
			if (msg != null) 
			{
				int tick = Integer.valueOf(msg.getContent());
				//System.out.println("Agent "+myAgent.getAID().getName()+ " receiving tick count " + tick);
				CurrentTickCount = tick;
				if(CurrentTickCount >= TickAgent.N_TICKS_TO_SYNC)
				{
					CurrentTickCount -= TickAgent.N_TICKS_TO_SYNC;;
					OnTickAction();
				}
			}
			else {
				block();
			}
		}
	}
	
}
